package com.test.redis_demo.util;

import com.test.redis_demo.model.CommonValue;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {

    //遍历所有cookie，找到需要的那个cookie
    public static String getCookieValue(HttpServletRequest request, String cookiName) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length <= 0) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(cookiName)) {
                return cookie.getValue();
            }
        }
        return null;
    }

    public static void setCookie(HttpServletResponse response, String token){
        Cookie cookie = new Cookie(CommonValue.USER_TOKEN, token);
        cookie.setMaxAge(3600*24);
        cookie.setPath("/");//设置为网站根目录
        response.addCookie(cookie);
    }
}
